﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Markup;
using System.Diagnostics;

namespace RichTextEditor.Controls
{
    /// <summary>
    /// Interaction logic for BindableRichTextbox.xaml
    /// </summary>
    public partial class Editor : UserControl
    {
        private BitmapImage image;
        private string richText;
        public EventHandler OnCtrlEnterKey;

        public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(Editor), new PropertyMetadata(TextPropertyChanged));
        public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("Image", typeof(BitmapImage), typeof(Editor), new PropertyMetadata(ImagePropertyChanged));
        
        public Editor()
        {
            InitializeComponent();
        }

        private static void ImagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((Editor)d).SetImage((BitmapImage)e.NewValue);
        }

        private static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((Editor)d).SetText((string)e.NewValue);
        }

        private void SetImage(BitmapImage image)
        {
            this.image = image;
        }

        public void SetFocus()
        {
            mainRTB.Focus();
        }

        private void SetText(string text)
        {
            this.Text = text;

            mainRTB.Document.Blocks.Clear();

            if (!string.IsNullOrEmpty(text))
            {
                using (MemoryStream xamlMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(text)))
                {
                    ParserContext parser = new ParserContext();
                    parser.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                    parser.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
                    FlowDocument doc = new FlowDocument();
                    Section section = XamlReader.Load(xamlMemoryStream, parser) as Section;

                    mainRTB.Document.Blocks.Add(section);
                }
            }
        }

        public BitmapImage Image
        {
            get
            {
                var blocks = mainRTB.Document.Blocks;

                if (blocks.FirstBlock is BlockUIContainer && blocks.FirstBlock == blocks.LastBlock)
                {
                    var container = (BlockUIContainer)blocks.FirstBlock;

                    if (container.Child is Image)
                    {
                        var image2 = (Image) container.Child;

                        image = (BitmapImage) image2.Source;
                    }
                }

                SetValue(ImageProperty, image);

                return image;
            }

            set
            {
                image = value;

                var container = new BlockUIContainer();

                container.Child = new Image { Source = image, Width = image.PixelWidth, Height = image.PixelHeight };

                mainRTB.Document.Blocks.Clear();
                mainRTB.Document.Blocks.Add(container);

                SetValue(ImageProperty, value);
            }
        }

        public string Text
        {
            get 
            {
                TextRange tr = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);

                richText = string.Empty;

                using (MemoryStream ms = new MemoryStream())
                {
                    tr.Save(ms, DataFormats.Xaml);
                    richText = ASCIIEncoding.Default.GetString(ms.ToArray());
                }

                SetValue(TextProperty, richText);

                return richText;
            }
            
            set 
            {
                richText = value;

                SetValue(TextProperty, value);
            }
        }

        private void mainRTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
            {
                OnCtrlEnterKey(this, e);
            }
        }
    }
}
